using System.Collections.Generic;
using System.Collections;

namespace Com.ContentRendering.Api.DataEngine.Handler.Self
{
    /// <summary/>
    internal class EnumerableSelfHandler : AbstractSelfHandler
    {
        /// <summary/>
        internal EnumerableSelfHandler(
            ReflectionCache reflectionCache,
            object value)
            : base(
            reflectionCache,
            value) { }

        /// <summary/>
        internal override IEnumerator<object> Parse()
        {
            // this must come before the enumerator test because some of the enumerator classes do
            // not implement the reset method ... which will cause the enumerator test to fail
            // although using ienumerable has more overhead ... it is less likely to fail

            // if the object doesn't implement the enumerable interface then move on
            if (!typeof(IEnumerable).IsInstanceOfType(this._value))
            {
                return base._successor.Parse();
            }

            // rather than just returning the enumerator, copy its values to a new list ... although this
            // seems like a waste of resources, it is a good idea since the lifetime of the enumerator is not known

            IEnumerable enumerable = (IEnumerable)this._value;

            List<object> parsedValues = new List<object>();

            // copy each value to the list
            foreach (object parsedValue in enumerable)
            {
                parsedValues.Add(parsedValue);
            }

            return parsedValues.GetEnumerator();        
        }
    }
}
